package com.cyx.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyx.common.core.domain.TableDataInfo;
import com.cyx.friend.domain.question.Question;
import com.cyx.friend.domain.question.dto.QuestionQueryDTO;
import com.cyx.friend.domain.question.es.QuestionES;
import com.cyx.friend.domain.question.vo.QuestionDetailVO;
import com.cyx.friend.domain.question.vo.QuestionVO;
import com.cyx.friend.elasticsearch.QuestionRepository;
import com.cyx.friend.manager.QuestionCacheManager;
import com.cyx.friend.mapper.question.QuestionMapper;
import com.cyx.friend.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // 先从es中获取数据总数
        long count = questionRepository.count();
        // es中没有
        if(count <= 0) {
            refreshQuestion(); // 把数据库中的数据同步到es
        }
        String keyword = questionQueryDTO.getKeyword();
        Integer difficulty = questionQueryDTO.getDifficulty();
        // 构造Sort，用来构造pageable
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 后面的查询需要传入pageable
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        Page<QuestionES> questionESPage;
        // 根据传入的参数查询
        if(difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if(StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if(difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else {
            questionESPage = questionRepository.findByContentOrTitleAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        // 查询完成之后，先判断是否有数据
        long total = questionESPage.getTotalElements();
        if(total <= 0) {
            return TableDataInfo.empty(); // 没数据返回空
        }
        // 先获取es查到的数据
        List<QuestionES> questionESList = questionESPage.getContent();
        // 再转换为VO返回
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList, total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if(questionES != null) {
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        Question question = questionMapper.selectById(questionId);
        if(question == null) {
            return null;
        }
        BeanUtil.copyProperties(question, questionDetailVO);
        refreshQuestion();
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if(listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if(listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    // 把数据库中的题目数据同步给es
    private void refreshQuestion() {
        // 先从数据中拿到数据
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        // 数据库中没有，直接返回
        if(CollectionUtil.isEmpty(questionList)) {
            return;
        }
        // 把查到的数据转换为es中存储的格式
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        // 数据存到es中
        questionRepository.saveAll(questionESList);
    }
}
